const getUserAvatar = function () {
  // 获取头像
  return new Promise(resolve => {
    wx.getSetting({
      success: (res) => {
        if (res.authSetting['scope.userInfo'] != undefined && res.authSetting['scope.userInfo'] === false) {
          // 调用过了getUserAvatar接口, 并且被用户拒绝
          wx.showModal({
            title: '"车车侠"需要获取您的地理位置',
            content: '需要获取您的地理位置, 请确认授权, 否则地图功能将无法使用',
            success: function (res) {
              if (res.cancel) {
              } else if (res.confirm) {
                wx.openSetting({
                  success: function (data) {
                    if (data.authSetting["scope.userLocation"] == true) {
                      wx.showToast({
                        title: '授权成功',
                        icon: 'success',
                        duration: 5000
                      })
                      //如果用户授权的话，调用getUserAvatart的API
                      wx.getUserAvatar({
                        type: 'gcj02',
                        success: function (res) {
                          const latitude = Number(res.latitude)
                          const longitude = Number(res.longitude)
                          resolve({latitude, longitude})
                        }
                      })
                    } else {
                      wx.showToast({
                        title: '授权失败',
                        icon: 'success',
                        duration: 5000
                      })
                    }
                  }
                })
              }
            }
          })
        } else {
          console.log(res)
          console.log('第一次调用wx.getUserInfo')
          // 第一次调用wx.getUserInfo或者调用过并且用户允许授权, 直接调用即可
          wx.getUserInfo({
            success: function(res) {
              // console.log(res.userInfo.avatarUrl)
              resolve(res.userInfo.avatarUrl)
            },
            fail (res) {
              // console.log(res)
            }
          })

        }
      }
    })
  })
}

module.exports = getUserAvatar